package com.sdkx.app;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.Timer;
import java.util.TimerTask;

public class TimerService extends Service implements View.OnClickListener{
    private final String TAG = TimerService.class.getSimpleName();
    private WindowManager.LayoutParams layoutParams;
    private WindowManager windowManager;
    private boolean isPause =false;
    private Timer timer;
    private long counter =0;
    private TextView textView_time;
    private Button button_pause;
    private Button button_end;
    private View serviceView;

    public TimerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        showFloatingWindow();
        initTimer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG,"onStartCommand()");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestory()");
    }

    private void initTimer(){
        final TimerHandler timerHandler = new TimerHandler();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if(!isPause) {
                    counter++;
                    Message message = new Message();
                    message.what = TimerHandler.UPDATE_TIME;
                    timerHandler.sendMessage(message);
                }
            }
        };
        timer = new Timer();
        timer.scheduleAtFixedRate(task,1000,1000);
    }

    private void showFloatingWindow(){
        //获取WindowManager服务
        windowManager = (WindowManager)getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        //获取悬浮窗布局
        serviceView = LayoutInflater.from(this).inflate(R.layout.floating_window,null);
        serviceView.setOnTouchListener(new FloatingOnTouchListener());
        textView_time = (TextView)serviceView.findViewById(R.id.textView_time);
        button_pause =  (Button)serviceView.findViewById(R.id.buttonPause);
        button_end = (Button)serviceView.findViewById(R.id.buttonEnd);
        button_pause.setOnClickListener(this);
        button_end.setOnClickListener(this);
        //设置LayoutParam
        layoutParams = new WindowManager.LayoutParams();
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.width =WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height =WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.x = 300;
        layoutParams.y = 300;
//        layoutParams.alpha = 0.5f;
        windowManager.addView(serviceView,layoutParams);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.buttonPause:
                if(!isPause){
                    button_pause.setText("继续");
                    //暂停
                }else {
                    //继续
                    button_pause.setText("暂停");
                }
                isPause = !isPause;
                break;
            case R.id.buttonEnd:
                timer.cancel();
                windowManager.removeView(serviceView);
                serviceView = null;
                stopSelf();
                //结束计时
                break;
            default:
                break;
        }
    }

    private class FloatingOnTouchListener implements View.OnTouchListener{
        private int x;
        private int y;

        @Override
        public boolean onTouch(View view,MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }
    }

    private class TimerHandler extends Handler{
        public static final int UPDATE_TIME=0;
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TIME:
                    int hour =(int)(counter/3600);
                    int minute =(int)((counter%3600)/60);
                    int second = (int)((counter%3600)%60);
                    textView_time.setText(format(hour)+":"+format(minute)+":"+format(second));
                    break;
                default:
                    break;
            }
        }
    }
    private String format(int value){
        if(value>9){
            return String.valueOf(value);
        }else {
            return "0"+value;
        }
    }
}
